/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
    
    int x, y, num, flag=0;
    struct ListNode * p=l1, * q=l2;
    struct ListNode * cur = (struct ListNode *)malloc(sizeof(struct ListNode));
    cur->next = 0;

    struct ListNode * ret = cur;

    while(p!=0 || q!=0)
    {
        if (p!=0) {
            x = p->val;
            p = p->next;
        } else {
            x = 0;
        }
        if (q!=0) {
            y = q->val;
            q = q->next;
        } else {
            y = 0;
        }

        num = x + y + flag;
        flag = num / 10;
        num = num % 10;

        cur->next = (struct ListNode *)malloc(sizeof(struct ListNode));
        cur = cur->next;
        cur->val = num;
        cur->next = 0;
    }
    if(flag!=0)
    {
        cur->next = (struct ListNode *)malloc(sizeof(struct ListNode));
        cur = cur->next;
        cur->next = 0;
        cur->val = flag;
    }

    return ret->next;
}
